<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');



class Bulk extends MY_Controller{
    private $target_dir='';
    private $fields = array(
        'account_name'=>0,
        'fname'=>0,
        'lname'=>0,
        'password'=>0,
        'email'=>0,
        'store_name'=>0,
        'status'=>0, // If they upload zero status, I must delete
        // 'start_time'=>0, // Start time 07:00 in template but stored in DB as microtime
        // 'endtime'=>0,
    );
    
    public function __construct() {
        parent::__construct();
        //$this->acl_auth->restrict_access('admin');
        $this->target_dir = BASEPATH.'../import/';

        $this->acl_auth->restrict_access('admin');

    }
    
    /**
     * Only login user have access on this one
     */
	public function index()
    {
        //landing page
        $d=array();
        $d['title']='Bulk Upload';
        $d['basepath']=BASEPATH.'../import/';
        
        $d['files']=array('text.csv','import-activate.csv');
        $d['files']=scandir($this->target_dir);
        unset($d['files'][0]);unset($d['files'][1]); // remove current and upper data..
        
        $views['_tabs'] = 'user/tabs';
        //$views['_userform'] = 'user/user_form';
        $views['_content'] = 'user/bulkupload';
        $this->template->load('user/admin', $views, $d);    

    }
    
    
    
    /**
     * Upload the files,.
     */
    public function upload()
    {
        $prefix = 'import-'.date('YmdHis');
        $uploadOk = 1;
        
        // Check if image file is a actual image or fake image
        if(isset($_POST["submit"])) {
            $FILE = $_FILES["filename"];
            $tmpfilename = $FILE["tmp_name"];
            if($tmpfilename){
                $uploadfile = $this->target_dir . basename($prefix.'-'.$FILE["name"]);

                if (preg_match('/\.csv$/i',$uploadfile)){
                   // echo 'OK: '.$uploadfile;
                    if(@move_uploaded_file($tmpfilename, $uploadfile)){
                        // TODO, verify the needed. Delete it if NOT valid
                        //$this->load->helper('tiangge_file'); // Load the tiannge_file_helper.php            
                        //$file =  $this->target_dir.$file."\n";
                        //echo $file;
                        //$header = tingge_read_file($file, 1);

                        // if (If not valid){
                        // $this->load->helper('file');
                        // delete_files();
                        //}
                        $this->load->model('audit_model');
                        try{
                            $this->audit_model->save(Audit_model::UPLOAD, array(
                                'user'=>$this->session->userdata('user_id'),
                                'msg' => 'Upload file: '.$prefix.'-'.$FILE["name"]
                            ));
                        }  catch (Exception $e){
                            
                        }
                        $this->session->set_flashdata('success','File successfully uploaded.');
                    }else{
                        $this->session->set_flashdata('error','Failed to upload a file');
                    }

                }else{
                   // echo 'FAILED NOT CSV: '.$tmpfilename." - ".$target_file;
                    $this->session->set_flashdata('error','Invalid file format');
                    // redirect to error page
                }
            }else{
                $this->session->set_flashdata('error','Please select a file.');
            }
        }else{
            $this->session->set_flashdata('error','Failed to upload a file.');
            // redirect to error page
        }
        log_message('error', 'Upload done');
        redirect('bulk/index');
        ///redirect('admin/'.$path);
    }

    /**
     * Process the bulk upload file
     * 
     */
    public function process()
    {
        if(isset($_POST["process"])) {
            $file = $this->input->post('file');
            
            $file =  trim($file); 
            if ($file){
                $file =  $this->target_dir.$file;
                if (file_exists($file)){
                    $this->load->helper('tiangge_file'); // Load the tiannge_file_helper.php
                    if (preg_match('/delete/i', $file)){
                        // Delete Process
                        // account_name

                        $users = tingge_read_file($file, -1);
                        unset($users[0]); // remove the header
                        foreach ($users as $key => $user){
                            log_message('info', 'Deleting '.$user[0]);
                            $this->acl_auth->delete($user[0]);
                        }
                        $this->load->model('audit_model');
                        try{
                            $this->audit_model->save(Audit_model::PROCESS, array(
                                'user'=>$this->session->userdata('user_id'),
                                'msg' => 'Process Deleting file: '.  basename($file)
                            ));
                        }  catch (Exception $e){
                            
                        }                        
                        $this->session->set_flashdata('success', 'Successfully deleted.');
                        rename($file,$this->target_dir.'../archived/'.$this->input->post('file'));
                    }else if (preg_match('/import/i', $file)){
                        //echo $file;
                        $users = tingge_read_file($file, -1);
                        //var_dump($users);

                        $header = $users[0];
                        unset($users[0]);
                        // Process the list into the DB.
                        $data = array(
                            'id' => $this->input->post("id"), 
                            'login' => 0,
                            'status' => 1,
                        );
                        $skips = 0;
                        $writes = 0;
                        $skip = false;

                        foreach ($users as $key => $user){
                            foreach ($user as $k => $value) {
                                $data[$header[$k]]=$value;
                                if (!trim($value)) $skip=true;
                            }
                            if ($skip){
                                $skip=false;
                                $skips++;
                            }else{
                                $writes++;
                                $this->acl_auth->register($data, 2/*user*/);
                            }
                        }
                        $this->load->model('audit_model');
                        try{
                            $this->audit_model->save(Audit_model::PROCESS, array(
                                'user'=>$this->session->userdata('user_id'),
                                'msg' => 'Process provision file: '.basename($file)
                            ));
                        }  catch (Exception $e){}                        
                        
                        rename($file,$this->target_dir.'../archived/'.$this->input->post('file'));
                        $this->session->set_flashdata('success', 'File processed succesfully.');
                    }else{
                        // Not valid file.
                        $this->session->set_flashdata('error', 'Please select a file.');
                    }
                }// if (file_exists($file)){
            }
            else{
                // File DOESNT Exists
                $this->session->set_flashdata('error', 'Please select another file.');
            }
            
            // I expect that there data is Valid...
            // I will going to move the file for safe keeping and audit
            
        }
        
        redirect('bulk');
    }

    /**
     * Export  users
     * 
     */
    public function export()
    {

        $this->load->model('user_model', 'um');
        $this->load->helper('file');
        $this->load->helper('download');
        $file = 'users.csv';
        
        $tmpfile = $this->target_dir.'../archived/temp-'.$file;
        
        $data = array('User Profile','Name','Username','E-mail');
        $users = $this->um->get_all_user(null); // get all users
        $fp = fopen($tmpfile, 'w');
        if ($fp){
            fputcsv($fp, $data);
            foreach ($users as $k => $user){
                $data = array(
                    $user->name==='admin'?'Admin':'Tiangge',
                     $user->fname.' '.$user->lname,
                     $user->account_name,
                     $user->email,
                );

                fputcsv($fp, $data);
    //            write_file($tmpfile, json_encode($data)."\n", 'a+');            
            }
            fclose($fp);
        }
        
  
        $this->output->set_header('Pragma: public;')
            ->set_header('Expires: 0')
            ->set_header('Cache-Control: must-revalidate, post-check=0, pre-check=0')
            ->set_header("Content-Type: text/csv")
            ->set_header('Content-Transfer-Encoding: binary')
            ->set_header('Content-Disposition: attachment; filename="'.$file.'"')
            ->set_header('Connection: close')
            ->set_header('Content-Length: '.filesize($tmpfile))
            ->set_output(file_get_contents($tmpfile))
            ;

    }
    
} //   
